<?php 
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Category;
use App\Advposition;
use App\Advcontent;
class AdvController extends Controller{
	function index(){
		//获取广告记录
		$cols = Advcontent::select('advcontent.*','category.cname',"advposition.namer")
			->leftJoin('category',"category.id",'=','advcontent.cid')
			->leftJoin('advposition','advposition.id','=','advcontent.advposid')
			->paginate(5);
		return view('admin/adv/index',['cols'=>$cols]);
	}
	function add(){
		$cateArr = Category::getTree();
		//获取所有的广告位
		$advposCols = Advposition::get();
		return view('admin/adv/add',['cateArr'=>$cateArr,'advposCols'=>$advposCols]);
	}
	function edit($id){
		//根据id，获取广告内容记录
		$ob = Advcontent::where('id',$id)->first();
		$cateArr = Category::getTree();
		//获取所有的广告位
		$advposCols = Advposition::get();
		return view('admin/adv/edit',['cateArr'=>$cateArr,'advposCols'=>$advposCols,'ob'=>$ob]);
	}
	function doedit(Request $request){
		$arr = $request->all();
		$id = $arr['id'];
		unset($arr['_token']);
		unset($arr['upload']);
		$rows = Advcontent::where('id',$id)->update($arr);
		$message = $rows ? "修改成功" : "修改失败";
		return redirect('admin/adv/index')->with('message',$message);
	}
	function getadvpos(Request $request){
		$cid = $request->get('cid');
		//根据cid，广告位记录
		$cols = Advposition::where('cid',$cid)->get();
		$arr = $cols->toArray();
		return response()->json($arr);
	}
	function del($id){
		//删除图片
		$ob = Advcontent::where('id',$id)->first();
		$path = trim($ob->path,'|');
		$arr = explode('|',$path);
		foreach($arr as $v){
			@unlink("./upload/".$v);
		}
		//删除记录
		$rows = Advcontent::where("id",$id)->delete();
		$message = $rows ? "删除成功" : "删除失败";
		return redirect()->back()->with('message',$message);

	}
	/**
	保存图片
	**/
	function upload(Request $request){
		$arr = $request->all();
		if(isset($arr['upload'])){
			$imageOb = $arr['upload'];//UploadedFile
			$path = $imageOb->store('adv','my');
			if($path){
				$message = "图片上传成功";
				$result = "success";
			}else{
				$message = "图片保存失败";
				$result = "error";
			}
			$reArr = ['result'=>$result,'message'=>$message,'path'=>$path];
			echo json_encode($reArr);
			exit();
		}else{
			$reArr = ['result'=>'error','message'=>请选择图片,'path'=>''];
			echo json_encode($reArr);
			exit();
		}
		
	}
	function delimage(Request $request){
		$path = $request->get('path');//接收图片路径
		$re = @unlink("./upload/".$path);//删除图片
		if($re){
			return response()->json(['result'=>'success',"message"=>"删除成功"]);
		}else{
			return response()->json(['result'=>'error',"message"=>"删除失败"]);
		}
	}
	function doadd(Request $request){
		$arr = $request->all();
		$ob = Advcontent::create($arr);
		if($ob){
			return redirect('admin/adv/index')->with('message',"添加成功");
		}else{
			return redirect('admin/adv/add')->with('message',"添加失败");
		}
	}
}